
_ = require 'underscore'
fsp = require '../bin/libs/fs-promises'
Q = require 'q'
path = require 'path'
certificate = require '../db/Certificate'
file = require '../db/File'

#文件上传模块


module.exports = (app) ->

  #证书上传 依赖certificate_id
  app.post '/certificates/file/:certificate_id', app.uploader.single('certificate'), (req, res, next) ->
    console.log "上传证书: "
    certificate_id = req.params.certificate_id
    originalname = req.file.originalname
    filename = req.file.filename + originalname.substring(req.file.originalname.lastIndexOf('.'))
    uploadedPath = req.file.path
    dest_path = path.join app.get('certificate_path'), certificate_id, filename
    dest_dir = path.join app.get('certificate_path'), certificate_id
    download_url = "/certificates/file/#{certificate_id}/#{filename}"

    fsp.rename uploadedPath, dest_path
    .then ->
      new Promise (resolve, reject) ->
        c_file = {name: filename, original_name: originalname, owner_id: certificate_id, download_url: download_url}
        file.save c_file, (err, obj) ->
          return reject(err) if err
          resolve obj
    .then (obj) ->
      res.status(200).json {code: 0, message: 'successfully', data: obj}
    .catch (e) ->
      console.log e
      res.status(404).json {code: -1, message: 'upload Failed '}




  #证书文件下载 by certificate_id
  app.get '/certificates/file/:certificate_id/:filename_id', (req, res, next) ->
    file_path = path.join app.get('certificate_path'), req.params.certificate_id, req.params.filename_id
    res.sendFile file_path, (err) ->
      return res.status(404).json {code:-1, message:'Can\'t find file.'} if err
      console.log "sented #{req.params.filename_id}"

  #证书文件查询 by certificate_id
  app.get '/certificates/file/:certificate_id', (req, res, next) ->
    new Promise (resolve, reject) ->
      file.find owner_id: req.params.certificate_id, (err, result) ->
        return reject(err) if err
        resolve result
    .then (result) ->
      res.status(200).json {code: 0, message: 'successfully', data: result}
    .catch (e) ->
      res.status(404).json {code: -1, message: 'find Failed '}


  #证书文件删除
  app.delete '/certificates/file/:file_id', (req, res, next) ->
    new Promise (resolve, reject) ->
      file.findOne _id: req.params.file_id, (err, obj) ->
        return reject(err) if err
        resolve obj
    .then (obj) ->
      new Promise (resolve, reject) ->
       file_path = path.join app.get('certificate_path'), obj.owner_id, obj.name
       fsp.remove_safe file_path
       .then ->
         resolve()
    .then ->
      new Promise (resolve, reject) ->
        file.remove _id: req.params.file_id, (err, result) ->
          return reject(err) if err
          resolve result
    .then (result) ->
      res.status(200).json {code: 0, message: 'delete successfully'}
    .catch (e) ->
      res.status(404).json {code: -1, message: 'delete Failed'}
